<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../conf/config.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Exchange\AMQPExchangeType;

$exchange = 'topic'; // 交换器名称

try {
    $connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST); // 建立连接到RabbitMQ服务器
    $channel = $connection->channel(); // 建立通道
    $channel->exchange_declare($exchange, AMQPExchangeType::TOPIC, false, true, false); // 试探性声明一个交换机
    $routingKey = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'none.info'; // 获取routing_key,没有默认为'none.info'
    $messageBody = json_encode(array_slice($argv, 2), JSON_UNESCAPED_UNICODE); // 获取发送数据
    if (empty($messageBody)) throw new Exception('请输入消息'); // 没有传入消息提示错误
    $message = new AMQPMessage($messageBody, ['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]); // 定义消息
    $channel->basic_publish($message, $exchange, $routingKey); // 生产消息
    $channel->close();// 关闭通道
    $connection->close();// 关闭连接
} catch (Exception $e) {
    die($e->getMessage());
}